package javacvtest.sqladminserver.service;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import javacvtest.sqladminserver.DTO.LogResultDTO;
import javacvtest.sqladminserver.DTO.SqlLogDTO;
import javacvtest.sqladminserver.Mapper.SqlLog;
import javacvtest.sqladminserver.VO.LogVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.juli.logging.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
@Slf4j
public class LogService {


    @Autowired
    private SqlLog sqlLog;

    public List<LogVO> getLog(SqlLogDTO sqlLogDTO) {

        List<LogResultDTO> logResult = sqlLog.getLogInfo(sqlLogDTO);
        if(logResult.isEmpty())
            return null;
        log.info("查询到的logResult集合："+ logResult);

        List<LogVO> logVOList = new ArrayList<>();

        for(LogResultDTO logResultDTO : logResult){
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                // 解析 resultColumns 为 List<String>
                List<String> resultColumns = objectMapper.readValue(
                        logResultDTO.getResultColumns(),
                        new TypeReference<List<String>>() {}
                );
                // 解析 resultRows 为 List<List<Object>>
                List<List<Object>> resultRow = objectMapper.readValue(
                        logResultDTO.getResultRows(),
                        new TypeReference<List<List<Object>>>() {}
                );
                LogVO logVO =new LogVO();
                logVO.setDataLog(logResultDTO.getDataSql());
                log.info("查询到的sql："+ logResultDTO.getDataSql());
                logVO.setDataName(logResultDTO.getDataName());
                log.info("查询到的数据名："+ logResultDTO.getDataName());
                logVO.setResultColumns(resultColumns);
                log.info("查询到的字段：{}", resultColumns);
                logVO.setResultRow(resultRow);
                log.info("查询到的数据：{}", resultRow);
                logVOList.add(logVO);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("JSON解析失败");
            }

        }
        return logVOList;
    }
}
